package com.partners.controller;

import com.partners.annotation.BeanValid;
import com.partners.annotation.SimpleParam;
import com.partners.constant.ErrorMessageEnum;
import com.partners.constant.SuccessMessageEnum;
import com.partners.dao.dto.LoginInputDTO;
import com.partners.dao.bo.UserDO;
import com.partners.model.ApiResult;
import com.partners.model.BusinessException;
import com.partners.service.LoginService;
import com.partners.service.UserService;
import com.partners.utils.ApiResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 前台登录
 * @author liangyongle
 * @date 2018-12-14
 */
@RestController
@RequestMapping("login")
@Slf4j
public class LoginController {

    @Resource
    private LoginService loginService;


    @Resource
    private UserService userService;

    /**
     * 登录
     * @param loginInputDTO LoginInputDTO
     * @return
     * @throws
     */
    @PostMapping("login")
    public ApiResult login(@BeanValid @RequestBody LoginInputDTO loginInputDTO){
        Map<String,Object> result = loginService.checkLogin(loginInputDTO);
        return ApiResultUtil.ok(result);
    }


    /**
     * 用户绑定微信
     * @param id Integer
     * @return
     * @throws
     */
    @GetMapping("bind/{id}")
    public void bindUser(@PathVariable("id") Integer id){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        UserDO user = userService.getUserById(id);
        String  redirectUrl = "/loginPage/index/"+id;
        if(user != null){
          if(!user.getOpenid().equals("")){
              redirectUrl = "/loginPage/error/405";
          }
        }
        try {
            response.sendRedirect(redirectUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 发送验证码
     * @param phone
     * @return
     * @throws
     */
    @PostMapping("send_code")
    public ApiResult sendCode(@SimpleParam("phone") String phone){
        if(phone == null){
            throw BusinessException.of(ErrorMessageEnum.PHONE_NOT_FOUND);
        }
        loginService.sendCode(phone);
        return ApiResultUtil.ok(SuccessMessageEnum.SEND_SUCCESS);
    }

    /**
     * 验证验证码
     * @param phone
     * @return
     * @throws
     */
    @PostMapping("verify_code")
    public ApiResult verifyCode(@SimpleParam("phone") String phone,@SimpleParam("code") Integer code){
        String result = loginService.getValidCode(phone);
        return ApiResultUtil.ok(result);
    }

}
